import UIKit

//定位引用
import CoreLocation

/**
 * App定位信息类
 */
class AppLocationData: NSObject, CLLocationManagerDelegate {

    var cityClosure: ((String) -> Void)?

    /** 定位的当前国家 */
    private var _strCurrentCountry: String? = "中国"
    var strCurrentCountry: String? {
        return _strCurrentCountry
    }

    /** 定位的当前省份 */
    private var _strCurrentProvince: String?
    var strCurrentProvince: String? {
        return _strCurrentProvince
    }

    /** 定位的当前城市 */
    private var _strCurrentCity: String? = "成都"
    var strCurrentCity: String? {
        return _strCurrentCity
    }

    /** 定位的当前城市所在的区(eg:普陀) */
    private var _strCurrentArea: String?
    var strCurrentArea: String? {
        return _strCurrentArea
    }

    /** 定位的当前详细信息 */
    private var _strCurrentAddress: String?
    var strCurrentAddress: String? {
        return _strCurrentAddress
    }

    /**
     * 定位信息
     *
     * 经度：currLocation.coordinate.longitude
     * 纬度：currLocation.coordinate.latitude
     * 海拔：currLocation.altitude
     * 方向：currLocation.course
     * 速度：currLocation.speed
     *  ……
     */
    private var _currentLocation: CLLocation?
    var currentLocation: CLLocation? {
        if _currentLocation != nil {
            return _currentLocation!
        } else {
            return nil
        }
    }

    static var mange: AppLocationData?

    //定位对象
    private static var llocationManager: CLLocationManager?

    // MARK: - 类初始化
    override init() {
        super.init()

        AppLocationData.mange = self

        //单例
        if AppLocationData.llocationManager == nil {
            AppLocationData.llocationManager = CLLocationManager.init()
            AppLocationData.llocationManager?.delegate = self

            //设置精度
            /*
             kCLLocationAccuracyBest             精确度最佳
             kCLLocationAccuracyNearestTenMeters 精确度10m以内
             kCLLocationAccuracyHundredMeters    精确度100m以内
             kCLLocationAccuracyKilometer        精确度1000m以内
             kCLLocationAccuracyThreeKilometers  精确度3000m以内
             */
            AppLocationData.llocationManager?.desiredAccuracy = kCLLocationAccuracyBest

            //设置间隔距离(单位：m) 内更新定位信息
            //定位要求的精度越高，distanceFilter属性的值越小，应用程序的耗电量就越大。
            AppLocationData.llocationManager?.distanceFilter = 1000.0

            //开启定位
//            if AppDelegate.app?.isNetWork().0 == true {
            AppLocationData.llocationManager?.startUpdatingLocation()
//            }
        }

        //权限检测
        self.locationPermissionsCheck()

        //监听网络通知 K_APP_NET_WORK_NOTICE

//        NotificationCenter.default.addObserver(self, selector: #selector(networkListenAction(sender:)), name: NSNotification.Name(rawValue: K_APP_NET_WORK_NOTICE), object: nil)
    }

    //权限检测
    private func locationPermissionsCheck() {

        if CLLocationManager.locationServicesEnabled() == false {
            print("请确认已开启定位服务")
            return
        }

        // 请求用户授权
        if CLLocationManager.authorizationStatus() == .notDetermined {
            AppLocationData.llocationManager?.requestWhenInUseAuthorization()

//            if #available(8.0, *) {
//                AppLocationData.llocationManager?.requestAlwaysAuthorization()
//            }
        }
    }

    // MARK: - 网络监听
    func networkListenAction(sender: Notification) {

        let user = sender.userInfo

        if let codeArg = user?["code"] as? CVarArg, let code = String.init(format: "%@", codeArg).int, code == 200 {
            //网络已链接,开启定位
            AppLocationData.llocationManager?.startUpdatingLocation()
        }
    }

    // MARK: - CLLocationManagerDelegate
    //定位失败
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print("定位失败!详见：\(error)")
    }

    //定位成功
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        print("定位成功")

        //赋值
        self._currentLocation = locations.last

        // [S] 反编码以便获取其他信息
        let geoCoder: CLGeocoder = CLGeocoder.init()
        geoCoder.reverseGeocodeLocation(locations.last!, completionHandler: { (placemarks, _) in

            let placeMark: CLPlacemark = placemarks![0]

            //当前城市(把"市"过滤掉,否则 和 其他界面城市不匹配)
            self._strCurrentCity = placeMark.locality?.replacingOccurrences(of: "市", with: "")

            //详细地址
            self._strCurrentAddress = placeMark.addressDictionary?["FormattedAddressLines"] as? String

            //国家
            self._strCurrentCountry = placeMark.addressDictionary?["Country"] as? String

            //省份
            self._strCurrentProvince = placeMark.addressDictionary?["State"] as? String

            //区
            self._strCurrentArea = placeMark.addressDictionary?["SubLocality"] as? String

            /*
             * region:                               //地理区域
             * addressDictionary:[AnyHashable : Any] //可以使用ABCreateStringWithAddressDictionary格式化为一个地址
             * thoroughfare: String?                 //街道名
             * name:String?                          //地址
             * subThoroughfare: String?              //大道
             * locality: String?                     //城市
             * subLocality: String?                  // 社区,通用名称
             * administrativeArea: String?           // state, eg. CA
             * subAdministrativeArea: String?        // 国家, eg. Santa Clara
             * postalCode: String?                   // zip code, eg. 95014
             * isoCountryCode: String?               // eg. US
             * country: String?                      // eg. United States
             * inlandWater: String?                  // 湖泊
             * ocean: String?                        // 洋
             * areasOfInterest: [String]?            // 感兴趣的地方
             */
        })
        // [E] 反编码以便获取其他信息
    }

}
